package com.bjb.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * Base64和图片工具
 */
public class Base64ImageUtil {

    /**
     * Base64位字符串数据转为BufferedImage
     * @param base64String
     * @return
     */
    public static BufferedImage base64StringToBufferedImage(String base64String){
        BufferedImage image = null;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes = decoder.decodeBuffer(base64String);
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            image = ImageIO.read(in);
        } catch (IOException e){
            e.printStackTrace();
        }
        return image;
    }

    /**
     * BufferedImage转为Base64数据
     * @param bufferedImage
     * @param suffix
     * @return
     */
    public static String imageToBase64(BufferedImage bufferedImage, String suffix){
        byte[] data = null;
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, suffix, baos);
            data = baos.toByteArray();
        }catch (IOException e){
            e.printStackTrace();
        } finally {
            if (baos != null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

    /**
     * 计算Base64数据对应的文件大小
     * @param base64Pic
     * @return
     */
    public static int isBase64ImageSizeLegal(String base64Pic) {
        return base64Pic.length() - (base64Pic.length() / 8) * 2; //单位字节b
    }
}
